<template>
  <a-modal
    v-model:visible="formVisible"
    :title="getTitle"
    @ok="handleModalOK"
    @cancel="handleModalCancel"
    :confirm-loading="confirmLoading"
  >
    <a-form :model="formData" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="角色名">
        <span>{{ formData.name }}</span>
      </a-form-item>
      <a-form-item label="权限范围">
        <a-select
          :field-names="{ label: 'label', value: 'value' }"
          v-model:value="formData.dataScopeType"
          :options="dataScopeTypeOptions"
        ></a-select>
      </a-form-item>

      <a-form-item label="数据权限" v-if="showDataScopeTree">
        <a-tree
          checkable
          checkStrictly
          v-model:checkedKeys="checkedKeys"
          v-model:expandedKeys="dataScopeExpandedKeys"
          @check="handleChecked"
          :tree-data="dataScopeTreeData"
          :field-names="{
            children: 'children',
            title: 'name',
            key: 'id',
          }"
        >
        </a-tree>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script lang="ts">
export default {
  name: 'DataScopeModal',
};
</script>
<script setup lang="ts">
import { ref, computed, onMounted, watch, unref } from 'vue';
import { getDataScopeListByRole, addDataScope, getDeptList } from '/@/api/sys/system';
import { deepMerge } from '/@/utils/index';
import { Form, message } from 'ant-design-vue';

const useForm = Form.useForm;

// 数据范围（1：全部数据权限 2：自定数据权限 3：本部门及以下数据权限4：本部门数据权限	// 5：本人）
const dataScopeTypeOptions = [
  { label: '全部数据权限', value: 1 },
  { label: '自定数据权限', value: 2 },
  { label: '本部门及以下数据权限', value: 3 },
  { label: '本部门数据权限', value: 4 },
  { label: '本人', value: 5 },
];

const props = defineProps({
  visible: Boolean,
  data: Object,
});
const emit = defineEmits(['ok', 'update:visible']);
const formVisible = ref(false);

const formData = ref({
  id: '',
  name: '',
  dataScopeType: undefined,
  dataScopeList: [],
});

const dataScopeTreeData = ref([]);
const dataScopeExpandedKeys = ref([]);
const confirmLoading = ref<boolean>(false);
const checkedKeys = ref([]);

const { resetFields } = useForm(formData);
const getTitle = '分配数据权限';

watch(
  () => formVisible.value,
  (val) => {
    emit('update:visible', val);
  },
);

watch(
  () => props.visible,
  (val) => {
    formVisible.value = val;
    if (val) {
      resetFields();
      deepMerge(formData.value, props.data);
      checkedKeys.value = [];
      formData.value.dataScopeList = [];

      if (formData.value.id) {
        fetchRoleDataScopeData(formData.value.id);
      }
    }
  },
);

const fetchData = async () => {
  dataScopeTreeData.value = await getDeptList();
  if (dataScopeTreeData.value) {
    dataScopeExpandedKeys.value = [];
    dataScopeTreeData.value.forEach((item) => {
      if (item.parentId == 0) {
        dataScopeExpandedKeys.value.push(item.id);
      }
    });
  }
};

const fetchRoleDataScopeData = async (id) => {
  let list = await getDataScopeListByRole({ roleId: id });

  if (list) {
    list.forEach((item) => {
      checkedKeys.value.push(item);
    });
    formData.value.dataScopeList = checkedKeys.value;
  }
};

const showDataScopeTree = computed(() => (formData.value.dataScopeType == 2 ? true : false));

const handleChecked = (checkedKeys, e) => {
  formData.value.dataScopeList = checkedKeys.checked;
};

onMounted(() => {
  fetchData();
});
const handleModalCancel = () => {
  formVisible.value = false;
};
const handleModalOK = async () => {
  try {
    confirmLoading.value = true;
    await addDataScope(unref(formData));
    message.success('保存成功');
    formVisible.value = false;
    emit('ok', true);
  } finally {
    confirmLoading.value = false;
  }
};
</script>